<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DownOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { activeMerchant, addMerchantInfo, freezeMerchant, getMerchantDetail, getMerchantList, updateBankInfo, updateMerchantInfo } from '~@/api/merchant/index'

defineOptions({
  name: 'Merchant',
})
const userStore = useUserStore()
const { hasPermission } = userStore
const message = useMessage()
const columns = shallowRef([
  // {
  //   title: '序号',
  //   dataIndex: 'id',
  //   width: 70,
  // },
  {
    title: '商户编号',
    dataIndex: 'merchantId',
    width: 190,
  },
  {
    title: '商户名称',
    dataIndex: 'merchantName',
    width: 250,
  },
  {
    title: '收款账号名称',
    dataIndex: 'accountName',
    width: 300,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '未设'
      }
    },
  },

  {
    title: '收款账号',
    dataIndex: 'accountNo',
    width: 200,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '未设'
      }
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 100,

  },

  {
    title: '创建时间',
    align: 'center',
    dataIndex: 'createTime',
    width: 160,
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 300,

  },
])
const tradeOptions = shallowRef([])
const bankForm = ref()
const merchantForm = ref()
const channelOptions = shallowRef([])
const merchantOptions = shallowRef([])
const loading = shallowRef(false)
const merchantloading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const editInfo = shallowRef({
  accountName: void 0,
  accountNo: void 0,
  address: void 0,
  city: void 0,
  contactName: void 0,
  createTime: void 0,
  creator: void 0,
  email: void 0,
  gender: void 0,
  id: void 0,
  licenseNo: void 0,
  memo: void 0,
  merchantId: void 0,
  merchantName: void 0,
  needSplit: void 0,
  phone: void 0,
  province: void 0,
  rate: void 0,
  receiveAccountName: void 0,
  receiveAccountNo: void 0,
  status: void 0,
  updateTime: void 0,
  updateUser: void 0,

})
const formModel = reactive({
  platRequestNo: void 0,
  accountNo: void 0,
  appId: void 0,
  cardNo: void 0,
  tradeType: void 0,
  tradeDate: void 0,
  channel: void 0,
})
const statusOptions = shallowRef([
  { configKey: 'ACTIVE', configValue: '正常' },
  { configKey: 'UNACTIVE', configValue: '未激活' },
  { configKey: 'FREEZE', configValue: '已冻结' },
])
const tableSize = ref(['large'])
const merchantTitle = shallowRef('')
const open = ref(false)
const isShow = ref(false) // 二次确认密码
const merchantLoading = ref(false)

const addOpen = ref(false)// 新增商户
const bankOpen = ref(false)// 添加银行账户
const rules = computed(() => {
  return {
    accountName: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    accountNo: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    accountNoConfirm: [
      {
        required: true, // ✅ 用来显示 *，不单独触发校验
        message: '',
        trigger: 'change',
      },
      {
        validator: (rule, value) => {
          if (!value) {
            return Promise.reject('必填字段')
          }
          if (value !== formState.accountNo) {
            return Promise.reject('两次输入的账号不一致')
          }
          return Promise.resolve()
        },
        trigger: ['blur', 'change'],
      },

    ],
    rate: [
      { required: true, message: '必填字段', trigger: 'change' },
      {
        pattern: /^0(\.(\d{1,4})?)?$/,
        message: '请输入一个最大为 0.9999 的值',
      },
    ],

  }
})
const formState = reactive({
  id: null,
  accountNo: '',
  accountNoConfirm: '',
  accountName: '',
  rate: null,
})
const formMerchant = reactive({
  phone: '',
  merchantName: '',
  merchantId: '',
  contactName: '',
  email: '',
  licenseNo: '',
  address: '',
})

const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  getType()
  getChannel()
})
// 查询交易类型字典值
async function getType() {
  try {
    const res = await getTradeType()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    tradeOptions.value = res.data
  }
  catch (e) {
  }
  finally {
    console.log(11)
  }
}

// 查询充值提现字典值
async function getChannel() {
  try {
    const res = await getChannelName()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    channelOptions.value = res.data.data
  }
  catch (e) {
  }
  finally {
    console.log(22)
  }
}
// 查询商户列表
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const startDate = formModel.tradeDate?.[0]?.format('YYYY-MM-DD')
    const endDate = formModel.tradeDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getMerchantList({
      param: { ...formModel, startDate, endDate },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data?.pageInfo.total
    console.log(111, totalNum.value)
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 搜索商户
async function onSearch() {
  pagination.current = 1
  await init()
}

// 重置商户筛选
async function onReset() {
  formModel.accountNo = void 0
  formModel.merchantId = void 0
  formModel.merchantName = void 0
  formModel.status = void 0
  await init()
}
// 重置商户信息
function resetMerchant() {
  formMerchant.phone = void 0
  formMerchant.merchantName = void 0
  formMerchant.merchantId = void 0
  formMerchant.contactName = void 0
  formMerchant.email = void 0
  formMerchant.address = void 0
  formMerchant.licenseNo = void 0
}

// 编辑商户信息
async function handleEdit(record) {
  resetMerchant()
  loading.value = true
  try {
    const res = await getMerchantDetail(record?.id)
    // console.log(res)
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    addOpen.value = true
    formMerchant.id = res.data.id
    formMerchant.merchantId = res.data.merchantId
    formMerchant.merchantName = res.data.merchantName
    formMerchant.contactName = res.data.contactName
    formMerchant.phone = res.data.phone
    formMerchant.email = res.data.email
    formMerchant.address = res.data.address
    formMerchant.licenseNo = res.data.licenseNo
    merchantTitle.value = '编辑商户'
    loading.value = false
  }
  catch (e) {
    // router.push('/profile/basic')
    console.log(e)
    loading.value = false
  }
  finally {
    loading.value = false
  }
}

// 解冻账户
async function handleUnfreeze(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要解冻卡号为 ${record.cardNo} 的账户吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = resetUnfreeze({ cardNo: record.cardNo })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 激活账户
async function handleUnactive(record, text) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要${text}商户 ${record.merchantName} 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = activeMerchant(record.id)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 冻结账户
async function handleFreeze(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要冻结商户 ${record.merchantName} 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = freezeMerchant(record.id)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 返回
function handleReturn() {
  open.value = false
}
function cancelBank() {
  bankOpen.value = false
}
// 添加银行账户
function addBankAccount(record) {
  if (bankForm.value) {
    bankForm.value.resetFields()
  }
  formState.id = record.id
  formState.accountNo = record.accountNo
  // formState.accountNoConfirm = record.accountNo
  formState.accountName = record.accountName
  formState.rate = record.rate
  editInfo.value = record
  if (!editInfo.value.accountNo) {
    isShow.value = true
  }
  bankOpen.value = true
}

// 新增商户
function addMerchant() {
  merchantTitle.value = '新增商户'
  if (merchantForm.value) {
    merchantForm.value.resetFields()
  }

  resetMerchant()
  addOpen.value = true
  // window.open('#/menu/menu1', '_blank')
}
/**
 * 交易类型
 *
 */
function handleTradeType(type) {
  switch (type) {
    case 'DEFRAY':
      return '支付'
    case 'REFUND':
      return '退费'
    case 'RECHARGE':
      return '充值'
    default:
      return '提现'
  }
}
/**
 * 订单状态
 *
 */
function handleStatus(status) {
  switch (status) {
    case 'ACTIVE':
      return '正常'
    case 'UNACTIVE':
      return '未激活'
    default:
      return '已冻结'
  }
}

// 确认添加银行账户
async function handleOk() {
  try {
    await bankForm.value.validate()
    const { data } = await updateBankInfo(formState)
    message.success('保存成功')
    init()
    bankOpen.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}

// 确认新增商户
async function handleMerchant() {
  merchantLoading.value = true
  try {
    await merchantForm.value.validate()
    if (formMerchant.id) {
      const { data } = await updateMerchantInfo(formMerchant)
      merchantLoading.value = false
      addOpen.value = false
      message.success('保存成功')
      init()
    }
    else {
      const { data } = await addMerchantInfo(formMerchant)
      merchantLoading.value = false
      addOpen.value = false
      message.success('新增成功')
      init()
    }
  }
  catch (error) {
    merchantLoading.value = false
    // message.error('请检查表单填写是否正确')
  }
}
// 处理账号失焦以后二次确认账号事件
function handleBlur() {
  isShow.value = true
  console.log(isShow.value, editInfo.value.accountNo)
}

function cancelModal() {
  if (bankForm.value) {
    bankForm.value.resetFields()
  }
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

const expand = ref(false)
</script>

<template>
  <page-container>
    <div>
      <a-card mb-4>
        <a-form :label-col="{ span: 7 }" :model="formModel">
          <a-row :gutter="[15, 0]">
            <a-col :span="8">
              <a-form-item name="merchantId" label="商户编号">
                <a-input v-model:value="formModel.merchantId" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="merchantName" label="商户名称">
                <a-input v-model:value="formModel.merchantName" placeholder="模糊查询" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="status" label="状态">
                <a-select v-model:value="formModel.status" placeholder="请选择" allow-clear>
                  <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                    {{ item.configValue }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="accountNo" label="收款账号">
                <a-input v-model:value="formModel.accountNo" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :span="24" style="text-align: right">
            <a-col :span="24">
              <a-space flex justify-end w-full>
                <!-- :loading="loading" -->
                <a-button type="primary" @click="onSearch">
                  查询
                </a-button>
                <a-button @click="onReset">
                  重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <a-card title="商户列表">
        <template #extra>
          <a-space size="middle">
            <a-button v-if="hasPermission('merchant:info:add')" type="primary" @click="addMerchant()">
              <template #icon>
                <PlusOutlined />
              </template>
              新增商户
            </a-button>
          </a-space>
        </template>
        <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'defrayFee'">
              <span :style="{ color: record.defrayFee < 0 ? 'red' : 'black' }">{{ Number(record.defrayFee).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'status'">
              <span>
                <a-badge :color="record.status === 'ACTIVE' ? 'blue' : 'red'" />
                <!-- <span /> -->
                <span> {{ handleStatus(record.status) }}</span>
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <div class="action flex flex-center">
                <a v-if="record.status === 'ACTIVE'" @click="handleFreeze(record)">冻结</a>
                <a v-if="record.status === 'FREEZE'" @click="handleUnactive(record, '解冻')">解冻</a>
                <a v-if="record.status === 'UNACTIVE'" @click="handleUnactive(record, '激活')">激活</a>
                <span v-if="hasPermission('merchant:info:edit')">
                  <span class="middle-line">|</span>
                  <a @click="handleEdit(record)">修改账户信息</a>
                </span>
                <span v-if="hasPermission('merchant:bank:add')">
                  <span class="middle-line">|</span>
                  <a @click="addBankAccount(record)"> <span>{{ record.accountNo ? '查看' : '添加' }}</span>银行账户</a>
                </span>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 添加银行账户 -->
      <a-modal v-model:open="bankOpen" width="600px" :mask-closable="false" title="银行账户信息" :body-style="{ paddingTop: '30px', paddingBottom: '30px' }" ok-text="保存">
        <template #footer>
          <div v-if="!editInfo.accountNo">
            <a-button key="back" @click="cancelBank">
              取消
            </a-button>
            <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
              确定
            </a-button>
          </div>
        </template>
        <a-form
          ref="bankForm"
          :model="formState"
          :rules="rules"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item
            label="账户名："
            name="accountName"
          >
            <a-input v-model:value="formState.accountName" :disabled="editInfo.accountNo" placeholder="请输入工行账户的名称" />
          </a-form-item>
          <a-form-item
            label="账号："
            name="accountNo"
          >
            <a-input-number v-model:value="formState.accountNo" :disabled="editInfo.accountNo" style="width: 370px;" :controls="false" placeholder="请输入工行账号" @blur="handleBlur" />
          </a-form-item>
          <a-form-item
            v-if="!editInfo.accountNo"
            label="重复输入账号："
            name="accountNoConfirm"
          >
            <a-input-number v-model:value="formState.accountNoConfirm" style="width: 370px;" :controls="false" placeholder="请再次输入工行账号" />
          </a-form-item>
          <a-form-item
            label="手续费费率："
            name="rate"
          >
            <a-input-number v-model:value="formState.rate" :disabled="editInfo.accountNo" style="width: 370px;" :controls="false" placeholder="如收取2%手续费，请填入0.02，以此类推" />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 新增商户 -->
      <a-modal v-model:open="addOpen" width="850px" :mask-closable="false" :title="merchantTitle" :body-style="{ paddingTop: '30px', paddingBottom: '30px' }" ok-text="保存" :confirm-loading="merchantLoading" @ok="handleMerchant" @cancel="cancelModal">
        <a-form
          ref="merchantForm"
          class="form-row"
          :model="formMerchant"
          name="basic"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 18 }"
          autocomplete="off"
        >
          <a-form-item
            label="商户名称"
            name="merchantName"
            :rules="[
              { required: true, message: '必填字段' },
            ]"
          >
            <a-input v-model:value="formMerchant.merchantName" style="width: 500px;" />
          </a-form-item>
          <a-form-item
            label="商户编号："
          >
            <a-input v-model:value="formMerchant.merchantId" :disabled="formMerchant.merchantId" style="width: 400px;" />
          </a-form-item>
          <a-form-item
            label="联系人姓名："
          >
            <a-input v-model:value="formMerchant.contactName" style="width: 400px;" />
          </a-form-item>
          <a-form-item
            label="联系电话："
          >
            <a-input-number v-model:value="formMerchant.phone" style="width: 400px;" :controls="false" />
          </a-form-item>
          <a-form-item
            label="常用邮箱："
            name="email"
            :rules="[
              { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
            ]"
            help="请输入有效邮箱地址，如 abc@163.com / user@qq.com"
          >
            <a-input v-model:value="formMerchant.email" style="width: 400px;" />
          </a-form-item>
          <a-form-item
            label="营业执照号："
          >
            <a-input v-model:value="formMerchant.licenseNo" style="width: 400px;" />
          </a-form-item>
          <a-form-item
            label="公司地址："
          >
            <a-textarea v-model:value="formMerchant.address" style="width: 500px;" :rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </page-container>
</template>
